<?php

class Controller_Auth extends Controller {

    public function action_login() {
        $submit = !empty($_POST) ? true : false;
        if ($submit) {
            $token = $_POST['csrf'];
            if (!Security::check($token)) {
                Security::token(true);
                //exit('非法提交');
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(array('errno'=>100, 'errmsg'=>'非法提交'));
                exit;
            }
            
            $username = $_POST['username'];
            $password = $_POST['password'];
            $return_url = !empty($_GET['return_url']) ? $_GET['return_url'] : URL::site('/');
            
            $auth = new Model_Auth();
            $user = $auth->login($username, $password);
            if ($user) {
                $auth->complete_login($user);
                //$this->redirect($return_url);
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(array('errno'=>0, 'data'=>$return_url));
                exit;
            } else {
                Security::token(true);
                //exit('登录失败');
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(array('errno'=>101, 'errmsg'=>'登录失败'));
                exit;
            }
        }
        
        $this->template = View::factory('login');
    }
}
